package com.tsd.jxc.buy.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.core.annotation.CheckBind;
import com.tsd.core.annotation.DataFieldAuth;
import com.tsd.core.annotation.DataPermission;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.JxcConstants;
import com.tsd.jxc.buy.entity.JxcBuyOrder;
import com.tsd.jxc.buy.entity.JxcBuyOrderDetailExt;
import com.tsd.jxc.buy.entity.JxcBuyOrderExt;
import com.tsd.jxc.buy.entity.JxcBuyReturnBillExt;
import com.tsd.jxc.buy.service.JxcBuyOrderService;
import com.tsd.jxc.buy.vo.JxcBuyStockInfoVo;
import com.tsd.jxc.fin.job.JxcFinanceJob;
import com.tsd.jxc.req.JxcBuyOrderReqParamsVo;
import com.tsd.jxc.req.JxcBuyReturnBillReqParamsVo;
import com.tsd.jxc.setting.service.JxcSettingService;
import com.tsd.jxc.utils.JxcAutoApprovalUtil;
import com.tsd.jxc.vo.JxcSettingVo;
import com.tsd.jxc.vo.PrintVo;
import com.tsd.system.controller.SystemBaseController;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import com.tsd.thread.Callback;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：JxcBuyOrder采购订单 控制层
 *
 * @author Hillpool
 * @date 2022/07/29 15:00:45
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "进销存-采购订单", description = "采购订单的API描述")
public class JxcBuyOrderController extends SystemBaseController {

    @Resource
    private JxcBuyOrderService jxcBuyOrderService;
    @Resource
    private JxcFinanceJob jxcFinanceJob;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private JxcSettingService jxcSettingService;

    @ApiOperation(value = "根据sid获取采购订单", notes = "根据sid获取采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "采购订单sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getJxcBuyOrderBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcBuyOrderBySid() {
        return this.getJxcBuyOrderBySidMethod();
    }

    public HttpResult<Object> getJxcBuyOrderBySidMethod() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcBuyOrderExt orderExt = jxcBuyOrderService.queryBySid(sid);
            if (orderExt != null) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                setting.procDisplay(orderExt, GlobalSetting.TYPE_SUPPLIER);
                List<JxcBuyOrderDetailExt> detailExtList = orderExt.getDetail_list();
                if (!HlpUtils.isEmptyList(detailExtList)) {
                    ListUtil.forEach(detailExtList, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
                    orderExt.setDetail_list(detailExtList);
                }
            }
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                hr.setData(JxcBuyOrderReqParamsVo.transfer(orderExt, settingVo));
            } else {
                hr.setData(orderExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除采购订单", notes = "根据id删除采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "采购订单sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteJxcBuyOrders.action", method = RequestMethod.POST)
    public HttpResult<String> deleteJxcBuyOrders() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            jxcBuyOrderService.deleteJxcBuyOrders(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存采购订单", notes = "保存采购订单，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "采购订单", required = true, paramType = "body", dataType = "JxcBuyOrder")
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcBuyOrder.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> saveJxcBuyOrder() {
        return this.saveJxcBuyOrderMethod(null);
    }

    public HttpResult<Object> saveJxcBuyOrderMethod(Callback<JxcBuyOrder> callback) {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcBuyOrderReqParamsVo paramsVo = super.getParams(request, JxcBuyOrderReqParamsVo.class);
            JxcBuyOrderExt orderExt = paramsVo.convert();
            if (HlpUtils.isEmpty(orderExt.getId()) && HlpUtils.isEmpty(orderExt.getBuyer_sid())) {
                orderExt.setBuyer_sid(opUser.getGroup_person_sid());
                orderExt.setSys_group_sid(opUser.getGroup_sid());
            }
            if (callback != null) {
                callback.pre_action(orderExt, opUser);
            }
            jxcBuyOrderService.saveJxcBuyOrder(orderExt, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval(JxcAutoApprovalUtil.FIELD_AUTO_APPROVAL_BUY_ORDER, () -> {
                jxcBuyOrderService.changeJxcBuyOrderAuditState(Collections.singletonList(orderExt.getSid()), 1, opUser);
                // 判断是否自动生成收票申请
                JxcAutoApprovalUtil.autoApproval(JxcAutoApprovalUtil.FIELD_AUTO_GENERATE_BUY_INVOICE, () -> {
                    // 自动生收票申请
                });
            });
            if (callback != null) {
                callback.post_action(orderExt, opUser);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询采购订单", notes = "分页查询采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcBuyOrders.action", method = RequestMethod.POST)
    @DataPermission(code = "buyOrder")
    public HttpResult<Object> findJxcBuyOrders() {
        return this.findJxcBuyOrderList();
    }

    public HttpResult<Object> findJxcBuyOrderList() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, null);
            HlpUtils.copyIntegerValue(map, params, "audit_state", "audit_state", false, null);
            HlpUtils.copyIntegerValue(map, params, "order_type", "order_type", false, null);
            HlpUtils.copyIntegerValue(map, params, "un_pay", "un_pay", false, null);
            HlpUtils.copyIntegerValue(map, params, "export_excel", "export_excel", false, null);
            HlpUtils.copyIntegerValue(map, params, "invoice_state", "invoice_state", false, null);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_sid", "supplier_sid", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_name", "supplier_name", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_contract_name", "supplier_contract_name", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_contract_phone", "supplier_contract_phone", false, false);
            HlpUtils.copyStringValue(map, params, "buyer_name", "buyer_name", false, false);
            HlpUtils.copyStringValue(map, params, "review_person_name", "review_person_name", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "goods_name", "goods_name", false, true);
            HlpUtils.copyDateRangeValue(map, params, "order_date", false);
            HlpUtils.copyDateRangeValue(map, params, "req_delivery_date", false);
            HlpUtils.copyDateRangeValue(map, params, "req_receive_date", false);
            HlpUtils.copyDateRangeValue(map, params, "real_receive_date", false);
            HlpUtils.copyListValue(map, params, "person_list", "person_list", false, String.class);
            super.filterGroups(map, params);
            PageBean page = new PageBean(map);
            List<JxcBuyOrderExt> list = jxcBuyOrderService.findJxcBuyOrders(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询采购单库存", notes = "分页查询采购单库存")
    @ResponseBody
    @RequestMapping(value = "/findJxcBuyOrders4Stock.action", method = RequestMethod.POST)
    public HttpResult<Object> findJxcBuyOrders4Stock() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "goods_name", "goods_name", false, false);
            HlpUtils.copyIntegerValue(map, params, "order_type", "order_type", false, null);
            HlpUtils.copyStringValue(map, params, "stock", "stock", false, false);
            HlpUtils.copyIntegerValue(map, params, "stock_info", "stock_info", false, null);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "supplier_sid", "supplier_sid", false, false);
            HlpUtils.copyDateRangeValue(map, params, "order_date", false);
            HlpUtils.copyListValue(map, params, "invoice_type_list", "invoice_type_list", false, Integer.class);
            PageBean page = new PageBean(map);
            List<JxcBuyStockInfoVo> list = jxcBuyOrderService.findJxcBuyOrders4Stock(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询采购订单", notes = "分页查询采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcBuyOrdersIncludeDetail.action", method = RequestMethod.POST)
    public HttpResult<Object> findJxcBuyOrdersIncludeDetail() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, null);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_name", "supplier_name", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_contract_name", "supplier_contract_name", false, false);
            HlpUtils.copyStringValue(map, params, "supplier_contract_phone", "supplier_contract_phone", false, false);
            HlpUtils.copyStringValue(map, params, "buyer_name", "buyer_name", false, false);
            HlpUtils.copyStringValue(map, params, "review_person_name", "review_person_name", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyDateRangeValue(map, params, "order_date", false);
            HlpUtils.copyDateRangeValue(map, params, "req_delivery_date", false);
            HlpUtils.copyDateRangeValue(map, params, "req_receive_date", false);
            HlpUtils.copyDateRangeValue(map, params, "real_receive_date", false);
            PageBean page = new PageBean(map);
            List<JxcBuyOrderExt> list = jxcBuyOrderService.findJxcBuyOrdersIncludeDetail(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 审核/反审核
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeJxcBuyOrderAuditState.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> changeJxcBuyOrderAuditState() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcBuyOrderService.changeJxcBuyOrderAuditState(sidList, state, opUser);
            // 审核时判断
            if (state == 1) {
                // 判断是否自动生成收票申请
                JxcAutoApprovalUtil.autoApproval(JxcAutoApprovalUtil.FIELD_AUTO_GENERATE_BUY_INVOICE, () -> {
                    // 自动生收票申请
                });
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 作废
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelJxcBuyOrder.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> cancelJxcBuyOrder() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            jxcBuyOrderService.cancelJxcBuyOrder(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成入库单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcBuyOrder2InBill.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcBuyOrder2InBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            int qty = jxcBuyOrderService.genJxcBuyOrder2InBill(sidList, opUser);
            if (qty==0){
                return HttpResult.fail(ErrorCode.CODE_NO_DATA,"没有需要生成入库单的数据");
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
            hr.setData(qty);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成退货单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcBuyOrder2ReturnBill.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcBuyOrder2ReturnBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcBuyOrderService.genJxcBuyOrder2ReturnBill(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 获取退货单数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getJxcBuyOrder2ReturnBillData.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcBuyOrder2ReturnBillData() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcBuyReturnBillExt billExt = jxcBuyOrderService.getJxcBuyOrder2ReturnBillData(sid);
            if (billExt != null) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                setting.procDisplay(billExt, GlobalSetting.TYPE_SUPPLIER);
            }
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                hr.setData(JxcBuyReturnBillReqParamsVo.transfer(billExt, settingVo));
            } else {
                hr.setData(billExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成对账
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcFinanceAccountDetail4Buy.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcFinanceAccountDetail4Buy() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            Integer genNum = jxcBuyOrderService.genJxcFinanceAccountDetail4Buy(sidList, opUser);
            jxcFinanceJob.addAccountSet2PriorityQueue4Finance(DataSourceContextHolder.getDataSourceType());
            hr.setData(genNum);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取采购订单数据", notes = "打印获取采购订单数据")
    @ResponseBody
    @RequestMapping(value = "/queryJxcBuyOrderData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryJxcBuyOrderData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcBuyOrderExt> list = jxcBuyOrderService.queryJxcBuyOrderData4Print(sidList);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
            }
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询销售单选单", notes = "分页查询销售单选单")
    @ResponseBody
    @RequestMapping(value = "/findJxcBuyOrders4Select.action", method = RequestMethod.POST)
    public HttpResult<Object> findJxcBuyOrders4Select() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            if (!map.containsKey("group_list")) {
                map.put("group_list", Collections.singletonList(opUser.getGroup_sid()));
            }
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyIntegerValue(map, params, "order_type", "order_type", false, null);
            HlpUtils.copyStringValue(map, params, "sale_order_sid", "sale_order_sid", false, false);
            HlpUtils.copyListValue(map, params, "selected_detail_list", "selected_detail_list", false, String.class);
            HlpUtils.copyListValue(map, params, "group_list", "group_list", false, String.class);
            HlpUtils.copyDateRangeValue(map, params, "order_date", false);
            HlpUtils.copyStringValue(map, params, "group_sid", "group_sid", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "check_stock", "check_stock", false, false);
            PageBean page = new PageBean(map);
            List<JxcBuyOrderExt> list = jxcBuyOrderService.findJxcBuyOrders4Select(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
                for (JxcBuyOrderExt orderExt : list) {
                    List<JxcBuyOrderDetailExt> detailExtList = orderExt.getDetail_list();
                    if (!HlpUtils.isEmptyList(detailExtList)) {
                        ListUtil.forEach(detailExtList, t -> setting.procDisplay(t, GlobalSetting.TYPE_SUPPLIER));
                    }
                    orderExt.setDetail_list(detailExtList);
                }
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "导入采购单", notes = "导入采购单")
    @ResponseBody
    @RequestMapping(value = "/importJxcBuyOrder.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> importJxcBuyOrder() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcBuyOrderExt orderExt = super.getParams(request, JxcBuyOrderExt.class);
            if (HlpUtils.isEmpty(orderExt.getId()) && HlpUtils.isEmpty(orderExt.getBuyer_sid())) {
                orderExt.setBuyer_sid(opUser.getGroup_person_sid());
                orderExt.setSys_group_sid(opUser.getGroup_sid());
            }
            jxcBuyOrderService.importJxcBuyOrder(orderExt, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval("auto_approval_buy_order", () -> {
                jxcBuyOrderService.changeJxcBuyOrderAuditState(Collections.singletonList(orderExt.getSid()), 1, opUser);
            });
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 获取以销定购数据
     *
     * @return
     */
    @ApiOperation(value = "获取以销定购数据", notes = "获取以销定购数据")
    @ResponseBody
    @RequestMapping(value = "/getJxcSale2BuyData.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcSale2BuyData() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> saleOrderList = super.getParamsList("sale_order_list", String.class, false);
            List<String> saleOrderDetailList = super.getParamsList("sale_order_detail_list", String.class, false);
            JxcBuyOrderExt orderExt = jxcBuyOrderService.getJxcSale2BuyData(saleOrderList, saleOrderDetailList);
            orderExt.setBuyer_sid(opUser.getGroup_person_sid());
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                hr.setData(JxcBuyOrderReqParamsVo.transfer(orderExt, settingVo));
            } else {
                hr.setData(orderExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "以销定购保存采购订单", notes = "以销定购保存采购订单")
    @ResponseBody
    @RequestMapping(value = "/saveJxcBuyOrder4Sale2Buy.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> saveJxcBuyOrder4Sale2Buy() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcBuyOrderReqParamsVo paramsVo = super.getParams(request, JxcBuyOrderReqParamsVo.class);
            JxcBuyOrderExt orderExt = paramsVo.convert();
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            List<String> orderList = jxcBuyOrderService.saveJxcBuyOrder4Sale2Buy(orderExt, settingVo, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval("auto_approval_buy_order", () -> {
                jxcBuyOrderService.changeJxcBuyOrderAuditState(orderList, 1, opUser);
            });
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
